<?php

class Cache_Memcache extends Cache {

    protected $instant;

    public static function checkDriver() {
        return function_exists("memcache_connect");
    }

    function __construct() {
        if (!self::checkDriver()) {
            throw new Exception("Can't use this driver for your system!");
        }
        Yaf_Registry::set('memcache', new Memcache());
        $this->instant = Yaf_Registry::get('memcache');
        $this->connectServer();
    }

    private function connectServer() {
        $server = self::$options['memcache']['server'];
        if (count($server) < 1) {
            $server = array(
                "127.0.0.1:11211"
            );
        }

        foreach ($server as $name) {
            $s = explode(':', $name);
            if (!isset($this->checked[$name])) {
                $this->instant->addserver($s[0], $s[1]);
                $this->checked[$name] = 1;
            }
        }
    }

    protected function _set($key, $value = "", $tts = 300) {
        return $this->instant->set($key, $value, false, $tts);
    }

    protected function _get($key) {
        $x = $this->instant->get($key);
        if ($x == false) {
            return null;
        } else {
            return $x;
        }
    }

    protected function _delete($key) {
        $this->instant->delete($key);
    }

    protected function _exist($key) {
        $x = $this->get($key);
        if ($x == null) {
            return false;
        } else {
            return true;
        }
    }

    protected function _clean() {
        $this->instant->flush();
    }

    protected function _stats() {
        $res = array(
            "info" => "",
            "size" => "",
            "data" => $this->instant->getStats(),
        );
        return $res;
    }

}
